import json
import os
import sys
import time

from common.bdp_url_utils import bdp_url_utils
from common.content_type import ContentType
from common.time_bdp import time_bdp
from core.result_base import ResultBase
from api.excel import excel
from common.logger import logger
from common.user_agent import useragent
import urllib3

from operation.task import task_status

urllib3.disable_warnings()

BASE_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(BASE_PATH)



def excel_upload(access_token,filename,filepath):
    """
    文件上传接口（excel和scv）
    :param filename: 文件夹名称
    :param filepath : 文件的结对路径
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()

    payload = {
        # "key": key,
        # "_xsrf":_xsrf,
        # "filename":filename
    }

    headers = {
        "User-Agent": useragent.get_user_agent_one()
   }

    cookies = {
        "access_token":access_token
    }

    files = {'file': (filename, open(filepath, 'rb'),
                      ContentType.APPLICATION_FILE_UPLOAD.value)}

    res = excel.upload(params=payload, files=files,headers=headers,cookies=cookies)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("文件上传 ==>> 返回结果 ==>> {}".format(result.response.text))
    return result


def excel_preview(access_token,excel_id,_t=time_bdp.time_stamp_13(),_xsrf=None):
    """
    文件预览接口（excel和scv）
    :param excel_id: 文件id
    :param _t : 13位的时间戳
    :param _xsrf :
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()

    payload = {
        "excel_id": excel_id,
        "_t":_t,
        "_xsrf": _xsrf
    }

    headers = {
        "User-Agent": useragent.get_user_agent_one()
   }

    cookies = {
        "access_token":access_token
    }


    res = excel.preview(params=payload,headers=headers,cookies=cookies)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("文件预览 ==>> 返回结果 ==>> {}".format(result.response.text))
    return result



def excel_parser(access_token,excel_id,sheet_names,row_offsets,udt=None,_t=time_bdp.time_stamp_13(),_xsrf=None):
    """
    文件解析接口（excel和scv）
    :param excel_id: 文件id,必填项
    :param sheet_names :必填项
    :param row_offsets:必填项
    :param udt :
    :param _t :
    :param _xsrf:
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()
    payload = {
        "excel_id": excel_id,
        "sheet_names": json.dumps([sheet_names]),
        "row_offsets":json.dumps([row_offsets]),
        "udt":udt,
        "_t":_t,
        "_xsrf":_xsrf
    }

    headers = {
        "User-Agent": useragent.get_user_agent_one(),
        "Content-Type":ContentType.APPLICATION_X_WWW_FORM_URLENCODE.value
   }

    cookies = {
        "access_token":access_token
    }

    res = excel.parser(params=payload,headers=headers,cookies=cookies)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("文件解析 ==>> 返回结果 ==>> {}".format(result.response.text))
    return result


def excel_title_check(access_token,titles,_t=time_bdp.time_stamp_13(),_xsrf=None):
    """
    检查工作表名称接口（excel和scv）
    :param titles: titles
    :param _t :
    :param _xsrf:
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()
    payload = {
        "titles": json.dumps([titles]),
        "_t":_t,
        "_xsrf":_xsrf
    }
    headers = {
        "User-Agent": useragent.get_user_agent_one()
   }
    cookies = {
        "access_token":access_token
    }
    res = excel.title_check(params=payload,headers=headers,cookies=cookies)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("检查工作表名称 ==>> 返回结果 ==>> {}".format(result.response.text))
    return result

def excel_create(access_token,excel_id,sheet_names,tb_name,force_merge,folder_id="folder_root",_t=time_bdp.time_stamp_13(),_xsrf=None):
    """
    创建文件接口（excel和scv）
    :param excel_id: 文件id
    :param sheet_names :
    :param row_offsets:
    :param udt :
    :param _t :
    :param _xsrf:
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()

    payload = {
        "excel_id": excel_id,
        "sheet_names":json.dumps([sheet_names]),
        "tb_name":tb_name,
        "force_merge":force_merge,
        "folder_id":folder_id,
        "_t": _t,
        "_xsrf":_xsrf
    }

    headers = {
        "User-Agent": useragent.get_user_agent_one()
   }

    cookies = {
        "access_token":access_token
    }

    res = excel.create(params=payload,headers=headers,cookies=cookies)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("创建工作表 ==>> 返回结果 ==>> {}".format(result.response.text))
    return result



def excel_list(access_token,tb_id,_t=time_bdp.time_stamp_13(),_xsrf=None):
    """
    获取工作表的excel列表（excel和scv）
    :param tb_id: 工作表id
    :param _t :
    :param _xsrf:
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()

    payload = {
        "tb_id": tb_id,
        "_t": _t,
        "_xsrf":_xsrf
    }

    headers = {
        "User-Agent": useragent.get_user_agent_one()
   }

    cookies = {
        "access_token":access_token
    }

    res = excel.list(params=payload,headers=headers,cookies=cookies)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("获取工作表的excel列表 ==>> 返回结果 ==>> {}".format(result.response.text))
    return result


def upload_data(access_token,filename,filepath,titles,folder_id="folder_root"):
    """
    上传数据流程方法（excel和scv）
    :param filename: 文件名称
    :param filepath :文件路径
    :param titles:工作表名称
    :param folder_id:工作表新建到哪一层文件夹下，默认是根目录
    :return: 自定义的关键字返回结果 result
    """

    #1、调用文件上传接口
    excel_upload_result =excel_upload(access_token,filename,filepath)
    #获取到excel_id
    excel_id = excel_upload_result.payload["result"]["excel_id"]
    #2、调用文件预览接口
    excel_preview_result = excel_preview(access_token, excel_id, _t=time_bdp.time_stamp_13(), _xsrf=None)
    #获取到sheet_names和row_offsets
    sheet_names = excel_preview_result.payload["result"][0]["name"]
    row_offsets = excel_preview_result.payload["result"][0]["row_offset"]
    #3、调用文件解析接口
    excel_parser_result = excel_parser(access_token, excel_id, sheet_names, row_offsets)
    #获取到任务id
    task_id = excel_parser_result.payload["result"]
    #4、调用任务状态查询接口

    task_status_result = task_status(access_token, task_id)
    #暂时是写死到10秒，待后面优化
    time.sleep(10)
    excel_title_check(access_token, titles)
    force_merge = "0"
    result = excel_create(access_token, excel_id, sheet_names, titles, force_merge,folder_id)
    status_code = str(result.payload["result"][0]["status"])
    if status_code == "0":
        logger.info("文件名：{}， 文件路径：{},工作表： {} ,上传数据成功".format(filename, filepath,titles))
    else:
        logger.info("文件名：{}， 文件路径：{},工作表： {} ,上传数据失败".format(filename, filepath, titles))
    return result









